/**
 * @author Fang Lu, fanglupku@gmail.com
 * 2011-5-12
 */
package com.autotag;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TokenExtractor {
	public static Pattern Camel_Border_Pattern = Pattern.compile("[A-Z0-9_%\\s]"); 
	public static Pattern Camel_Content_Pattern = Pattern.compile("[a-z]"); 
	public static void main(String args[]){
		String testStr = "GetProject_IDFromMysqlByClassID";
		ArrayList<String> tList = extractTokenFromCamelString(testStr);
		for(int i=0; i<tList.size(); ++i){
			System.out.println(tList.get(i));
		}
		System.out.println(generateString(tList, " "));
	}
	public static String generateString(ArrayList<String> srcList, String delim){
		StringBuffer sb = new StringBuffer();
		for (int i=0; i<srcList.size(); ++i){
			sb.append(srcList.get(i));
			sb.append(delim);
		}
		return sb.toString();
	}
	public static ArrayList<String> mergeSingleChar(ArrayList<String> srcList){
		ArrayList<String> destList = new ArrayList<String>();
		
		StringBuffer sb = new StringBuffer();
		for (int i=0; i<srcList.size(); ++i){
			String thisToken = srcList.get(i);
			if (thisToken.equals("_")){
				continue;
			}
			if (thisToken.startsWith("_")){
				thisToken = new String(thisToken.substring(1));
			}
			if (thisToken.trim().length() ==0){
				continue;
			}
			if (thisToken.length() == 1){
				sb.append(thisToken);
			}else {
				if (sb.length() > 0){
					destList.add(sb.toString());
					sb.delete(0, sb.length());
				}
				destList.add(thisToken);
			}
		}
		if (sb.length() > 0){
			destList.add(sb.toString());
		}
		
		return destList;
	}
	public static ArrayList<String> extractTokenFromCamelString(String inputString){
		ArrayList<String> resultList = new ArrayList<String>();
		if (inputString == null){
			return resultList;
		}
		Matcher matcher = Camel_Border_Pattern.matcher(inputString);
		ArrayList<Integer> borderIndexList = new ArrayList<Integer>();
		boolean isFirst = true;
		while (matcher.find()){
			if (isFirst){
				isFirst = false;
				if (matcher.start() > 0){
					borderIndexList.add(0);
				}
			}
			borderIndexList.add(matcher.start());
		}
		for (int i=0; i<borderIndexList.size()-1; ++i){
			String thisToken = new String(inputString.substring(borderIndexList.get(i), borderIndexList.get(i+1)));
			resultList.add(thisToken.trim());
		}
		if (borderIndexList.size() > 0){
			String thisToken = new String(inputString.substring(borderIndexList.get(borderIndexList.size()-1)));
			resultList.add(thisToken.trim());
		}
		resultList = mergeSingleChar(resultList);
		return resultList;
	}
}
